package com.fsz.pachong.pachong.util;


import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 功能 PDF读写类
 *
 * @CreateTime 2011-4-14 下午02:44:11
 */
public class PDFUtil {
    private static Logger logger = LoggerFactory.getLogger(PDFUtil.class);
    private static CloseableHttpClient httpClient = HttpClients.custom().build();
    //  public static final String CHARACTOR_FONT_CH_FILE = "SIMFANG.TTF";  //仿宋常规
    public static final String CHARACTOR_FONT_CH_FILE = "SIMHEI.TTF";  //黑体常规

    public static final float MARGIN_LEFT = 50;
    public static final float MARGIN_RIGHT = 50;
    public static final float MARGIN_TOP = 50;
    public static final float MARGIN_BOTTOM = 50;
    public static final float SPACING = 20;


    /**
     * 读PDF文件，使用了pdfbox开源项目
     *
     * @param url
     */
    public static String readPDF(String url,String path,String fileName) {
        HttpGet httpGet = HttpClientConnectionManager.getGetMethod(url);
        File file = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            file = FileUtil.InputStreamFile(response.getEntity().getContent(), "utf-8",path,fileName);
            if(file != null) {
                // 新建一个PDF解析器对象
                PDFParser parser = new PDFParser(new RandomAccessBuffer(new FileInputStream(file)));
                // 对PDF文件进行解析
                parser.parse();
                // 获取解析后得到的PDF文档对象
                PDDocument pdfdocument = parser.getPDDocument();
                // 新建一个PDF文本剥离器
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setSortByPosition(true); //sort设置为true 则按照行进行读取，默认是false
                // 从PDF文档对象中剥离文本
                String result = stripper.getText(pdfdocument);
                FileWriter fileWriter = new FileWriter(new File("pdf.txt"));
                fileWriter.write(result);
                fileWriter.flush();
                fileWriter.close();
                System.out.println("PDF文件的文本内容如下：");
                System.out.println(result);
                return  result;
            }

        } catch (Exception e) {
            System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败！" + e);
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 测试pdf读取
     *
     * @param args
     */
    public static void main(String[] args) {
        readPDF("http://service.most.gov.cn/u/cms/static/201907/09141707pvlf.pdf","D:/test","test.pdf");
    }
}
